<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-button type="primary" @click='addRoledialogVisible = true'>添加角色</el-button>
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <!-- 三级权限的图  -->
          <template slot-scope="scope">
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'itemscenter']"
            >
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 === 0 ? '' : 'bdtop', 'itemscenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                    :v-for='item3 in item2.children'
                      type="warning"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                        </el-tag>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit"
            @click='openEditDialog(scope.row.id)'
            >编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" @click='removeRole(scope.row.id)'
            >删除</el-button>
            <el-button type="warning" icon="el-icon-setting" @click='showSetRightDialog(scope.row)'>
              分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog
    title="添加角色"
    :visible.sync="addRoledialogVisible"
    width="30%"
    @close='cancelAddRole'
    >
    <div>
      <el-form ref="addDialogFormRef" :model="addRoleInfo" label-width="100px">
        <el-form-item label="角色名称：">
          <el-input v-model="addRoleInfo.roleName">
          </el-input>
        </el-form-item>
        <el-form-item label='角色描述：'>
          <el-input v-model='addRoleInfo.roleDesc'>
          </el-input>
        </el-form-item>
      </el-form>
    </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAddRole">取 消</el-button>
        <el-button type="primary" @click="addRole">
          确 定
        </el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog title="添加"
    :visible.sync="setRightDialogVisible"
    width="50%"
    @close='defaultKey = [];'
    >
    <div>
      <el-tree
      :data="rightsList"
      show-checkbox
      node-key="id"
      :props="defaultProps"
      default-expand-all
      :default-checked-keys='defaultKey'
      ref='treeRef'
      >
    </el-tree>
    </div>
    <span slot="footer"
          class="dialog-footer">
      <el-button @click="setRightDialogVisible = false">取 消</el-button>
      <el-button type="primary"
                @click="setRolesRights">确 定</el-button>
    </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog
    title="编辑角色"
    :visible.sync="editRoleDialogVisible"
    width="30%"
    >
      <!-- 编辑角色的表单 -->
    <el-form :model="editRoleInfo" prop="rolename">
      <el-form-item label="角色名称：">
        <el-input v-model="editRoleInfo.roleName">
        </el-input>
      </el-form-item>

      <el-form-item label='角色描述：' prop='roleDesc'>
        <el-input v-model='editRoleInfo.roleDesc'>
        </el-input>
      </el-form-item>
    </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="eidtRole">
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  created() {
    this.getRolesList()
  },
  data() {
    return {
      rolesList: [], //角色列表
      rightsList: [], //权限列表
      addRoledialogVisible: false, //添加角色对话框开关
      setRightDialogVisible: false, //设置角色权限对话框开关
      editRoleDialogVisible: false, //编辑角色对话框开关

      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      defaultKey: [],
      thisRole: '',
      addRoleInfo: {
        roleName: '',
        roleDesc: ''
      },
      editRoleInfo: {}
    }
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      // console.log(res)
      this.rolesList = res.data
    },
    //删除ID对应的权限
    removeRightById(role, rightId) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          )
          if (res.meta.status !== 200) {
            this.$message.error(res.meta.msg)
            return
          }
          this.$message({
            type: 'success',
            message: res.meta.msg
          })
          role.children = res.data
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    //打开设置权限的对话框
    async showSetRightDialog(role) {
      //设置当前角色id
      this.thisRole = role.id

      const{ data: res } = await this.$http.get(`rights/tree`)
      if(res.meta.status !== 200) {
        this.$message.error('获取权限列表失败！')
        return
      }
      // console.log(res);
      this.rightsList = res.data

      this.getLeafKeys(role, this.defaultKey)

      this.setRightDialogVisible = true
    },
    //递归获取所有三级权限
    getLeafKeys(node, arr) {
      //没有子节点则把id传入 defaultKey 中
      if(!node.children) {
        // console.log(node);
        arr.push(node.id)
        return
      }
      //有子节点则遍历所有子节点
      node.children.forEach(element => {
        this.getLeafKeys(element, arr)
      })
    },
    //分配当前角色权限
    async setRolesRights() {
      //通过树形控件的引用来调用函数获取选中和半选中的节点id
      const keyArr = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]

      const keyStr = keyArr.join(',')

      //发起角色授权请求
      const { data: res } = await this.$http.post(`roles/${this.thisRole}/rights`, { rids: keyStr })
      // console.log(res);
      if(res.meta.status !== 200) {
        this.$message.error('角色授权失败')
        return
      }

      //授权成功，刷新列表 关闭对话框
      this.$message.success('角色授权成功！')
      this.getRolesList()
      this.setRightDialogVisible = false
    },
    //删除角色
    removeRole(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const { data: res } = await this.$http.delete('roles/' + id)
        if(res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
          return
        }
        this.$message.success(res.meta.msg)

        //刷新列表
        this.getRolesList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    //添加角色
    async addRole() {
      //发送添加角色的网络请求并接受结果
      const { data: res } = await this.$http.post('roles', this.addRoleInfo)

      //如果请求失败则返回错误信息
      if(res.meta.status !== 201) {
        this.$message.error(res.meta.msg)
        return
      }

      //添加成功

      //提示信息
      this.$message.success(res.meta.msg)

      //刷新成员列表
      this.getRolesList()

      //关闭对话框
      this.addRoledialogVisible = false
    },
    // 添加角色对话框按取消后清空addRoleInfo的内容
    cancelAddRole() {
      //清空信息
      this.addRoleInfo = {
        roleName: '',
        roleDesc: ''
      }
      //关闭对话框
      this.addRoledialogVisible = false
    }, //点击编辑角色按钮的事件
    async openEditDialog(id) {
      //打开对话框
      this.editRoleDialogVisible = true

      //根据id查找角色并保存到本地
      const { data: res } = await this.$http.get('roles/' + id)
      if(res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
        return
      }
      //查询成功 保存到本地
      this.editRoleInfo = res.data
      // console.log(this.editRoleInfo);
    },
    //编辑角色对话框点击确定按钮的事件
    async eidtRole() {
      //发送编辑的请求
      const { data: res } = await this.$http.put('roles/' + this.editRoleInfo.roleId, {
        roleName: this.editRoleInfo.roleName,
        roleDesc: this.editRoleInfo.roleDesc
      })

      if(res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
        return
      }

      //编辑成功
      this.$message.success('编辑角色成功！')

      //刷新列表
      this.getRolesList()

      //关闭对话框
      this.editRoleDialogVisible = false
    }
  }
}
</script>
<style lang="less">
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}
.itemscenter {
  display: flex;
  align-items: center;
}
</style>
